<template>
  <el-dialog
    v-model="dialogVisible"
    append-to-body
    :title="$t('form.setting.chooseUserDialogTitle')"
    v-if="dialogVisible"
    :fullscreen="screenWidth <= 768"
    :width="screenWidth <= 768 ? '95%' : '90%'"
  >
    <div class="app-container">
      <el-row :gutter="10">
        <el-col
          :lg="15"
          :md="15"
          :sm="24"
          :xs="24"
        >
          <!--用户数据-->
          <el-form
            v-show="showSearch"
            ref="queryFormRef"
            :inline="true"
            :model="queryParams"
            label-width="50px"
            size="default"
            label-position="left"
          >
            <el-row :gutter="5">
              <el-col
                :lg="7"
                :md="7"
                :sm="24"
                :xs="24"
              >
                <el-form-item
                  :label="$t('form.setting.userNameLabel')"
                  prop="userName"
                >
                  <el-input
                    class="input-width"
                    size="default"
                    v-model="queryParams.userName"
                    clearable
                    :placeholder="$t('form.setting.userNameLabel')"
                    @keyup.enter="handleQuery"
                  />
                </el-form-item>
              </el-col>
              <el-col
                :lg="7"
                :md="7"
                :sm="24"
                :xs="24"
              >
                <el-form-item
                  :label="$t('form.setting.nickNameLabel')"
                  prop="nickName"
                >
                  <el-input
                    class="input-width"
                    v-model="queryParams.nickName"
                    clearable
                    size="default"
                    :placeholder="$t('form.setting.nickNameLabel')"
                    @keyup.enter="handleQuery"
                  />
                </el-form-item>
              </el-col>
              <el-col
                :lg="7"
                :md="7"
                :sm="24"
                :xs="24"
              >
                <el-form-item
                  label-width="70px"
                  :label="$t('form.setting.phoneNumberLabel')"
                  prop="phonenumber"
                >
                  <el-input
                    class="input-width"
                    v-model="queryParams.phonenumber"
                    clearable
                    size="default"
                    :placeholder="$t('form.setting.phoneNumberLabel')"
                    @keyup.enter="handleQuery"
                  />
                </el-form-item>
              </el-col>
              <el-col
                :lg="2"
                :md="2"
                :sm="24"
                :xs="24"
              >
                <el-form-item>
                  <el-link
                    type="primary"
                    :underline="false"
                    @click="moreFilter = !moreFilter"
                  >
                    <el-icon>
                      <ele-ArrowDown />
                    </el-icon>
                    <span v-if="!moreFilter">{{ $t("form.setting.more") }}</span>
                    <span v-else>{{ $t("form.setting.less") }}</span>
                  </el-link>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="moreFilter">
              <el-col
                :lg="8"
                :md="8"
                :sm="24"
                :xs="8"
                :xl="8"
              >
                <el-form-item
                  label-width="70px"
                  :label="$t('system.userManagement.belongingDept')"
                  prop="deptId"
                >
                  <el-tree-select
                    size="default"
                    clearable
                    check-strictly
                    v-model="queryParams.deptId"
                    :data="deptOptions"
                    :props="{ value: 'id', label: 'label', children: 'children' }"
                    :placeholder="$t('system.userManagement.belongingDeptPlaceholder')"
                    default-expand-all
                  />
                </el-form-item>
              </el-col>
              <el-col
                :lg="8"
                :md="24"
                :sm="24"
                :xs="24"
                :xl="8"
              >
                <el-form-item
                  :label="$t('system.userManagement.userRoles')"
                  label-width="70px"
                  prop="roleIds"
                >
                  <el-select
                    size="default"
                    v-model="queryParams.roleIds"
                    multiple
                    clearable
                    collapse-tags
                    :placeholder="$t('formI18n.all.pleaseEnter')"
                  >
                    <el-option
                      v-for="item in roleList"
                      :key="item.id"
                      :label="item.roleName"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <div>
              <el-form-item>
                <el-button
                  size="default"
                  icon="ele-Search"
                  type="primary"
                  @click="handleQuery"
                >
                  {{ $t("formI18n.all.search") }}
                </el-button>
                <el-button
                  size="default"
                  icon="ele-Refresh"
                  @click="resetQuery"
                >
                  {{ $t("formI18n.all.reset") }}
                </el-button>
              </el-form-item>
            </div>
          </el-form>
          <el-table
            ref="userTableRef"
            v-loading="loading"
            :data="userList"
            row-key="id"
            @select="handleSelectionChange"
            @select-all="handleSelectionChange"
            :max-height="screenWidth <= 768 ? '400px' : 'auto'"
          >
            <el-table-column
              v-if="multiple"
              align="center"
              type="selection"
              width="50"
              :reserve-selection="true"
            />
            <el-table-column
              v-else
              label
              width="45"
            >
              <template #default="scope">
                <el-radio
                  v-model="radioId"
                  :value="scope.row.id"
                  @change="handleSingleUser(scope.row)"
                >
                  &nbsp;
                </el-radio>
              </template>
            </el-table-column>
            <el-table-column
              key="userId"
              align="center"
              :label="$t('form.setting.userTableUserId')"
              prop="id"
              width="100"
            />
            <el-table-column
              key="userName"
              :show-overflow-tooltip="true"
              align="center"
              :label="$t('form.setting.userTableUserName')"
              prop="userName"
            />
            <el-table-column
              key="nickName"
              :show-overflow-tooltip="true"
              align="center"
              :label="$t('form.setting.userTableNickName')"
              prop="nickName"
            />
            <el-table-column
              key="deptName"
              :show-overflow-tooltip="true"
              align="center"
              :label="$t('form.setting.userTableDeptName')"
              prop="dept.deptName"
            />
            <el-table-column
              key="phonenumber"
              align="center"
              :label="$t('form.setting.userTablePhoneNumber')"
              prop="phonenumber"
              width="130"
            />
            <el-table-column
              key="cpWxName"
              align="center"
              :label="$t('form.setting.cpWxUserName')"
              prop="cpWxName"
              width="130"
            />
            <el-table-column
              align="center"
              :label="$t('form.setting.userTableCreateTime')"
              prop="createTime"
              width="180"
            >
              <template #default="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              v-if="screenWidth <= 768"
              type="expand"
              width="50"
            >
              <template #default="props">
                <el-form
                  class="table-expand"
                  inline
                  label-position="left"
                >
                  <el-form-item :label="$t('form.setting.userTableDeptName')">
                    <span>{{ props.row.dept?.deptName }}</span>
                  </el-form-item>
                  <el-form-item :label="$t('form.setting.cpWxUserName')">
                    <span>{{ props.row.cpWxName }}</span>
                  </el-form-item>
                  <el-form-item :label="$t('form.setting.userTableCreateTime')">
                    <span>{{ parseTime(props.row.createTime) }}</span>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            v-model:limit="queryParams.size"
            v-model:page="queryParams.current"
            :total="total"
            @pagination="getList"
          />
        </el-col>
        <el-col
          :lg="9"
          :md="9"
          :sm="24"
          :xs="24"
        >
          <p class="title-text pl5">{{ $t("form.setting.selectUserTitle") }}</p>
          <el-table
            border
            :data="selectedUserList"
            max-height="500"
          >
            <template #empty>
              <el-empty :description="$t('client.table.noData')" />
            </template>
            <el-table-column
              key="userId"
              align="center"
              :label="$t('form.setting.userTableUserId')"
              prop="id"
            />
            <el-table-column
              key="userName"
              :show-overflow-tooltip="true"
              align="center"
              :label="$t('form.setting.userTableUserName')"
              prop="userName"
            />
            <el-table-column
              key="nickName"
              :show-overflow-tooltip="true"
              align="center"
              :label="$t('form.setting.userTableNickName')"
              prop="nickName"
            />
            <el-table-column
              align="center"
              class-name="small-padding fixed-width"
              :label="$t('form.setting.selectUserTableOperation')"
              width="160"
            >
              <template #default="scope">
                <el-button
                  icon="ele-Delete"
                  link
                  type="primary"
                  @click="deleteSelectedUserHandle(scope.row)"
                >
                  {{ $t("formI18n.all.delete") }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button
          size="default"
          @click="dialogVisible = false"
        >
          {{ $t("formI18n.all.cancel") }}
        </el-button>
        <el-button
          type="primary"
          size="default"
          @click="submitSelectedUserHandle"
        >
          {{ $t("formI18n.all.confirm") }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { nextTick, onMounted, reactive, ref } from "vue";
import { getDeptTree, getRoleList, pageUser } from "@/api/system/organization";
import { difference, uniqBy, findIndex } from "lodash-es";
import { parseTime, resetFormRef } from "@/utils/tduck";
import { treeselect } from "@/api/system/dept";
import { listRole } from "@/api/system/role";
import { useWindowSize } from "@vueuse/core";

const props = defineProps({
  // 多选
  multiple: {
    type: Boolean,
    default: true
  },
  // 不记录已选用户
  noRecord: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(["submit"]);

const radioId = ref(null);
const loading = ref(true);
const dialogVisible = ref(false);
const showSearch = ref(true);
const total = ref(0);
const userList = ref([]);
const selectedUserList = ref([]);
const defaultSelectRows = ref([]);
const removedSelectRows = ref([]);

const queryParams = reactive({
  current: 1,
  size: 5,
  userName: undefined,
  nickName: undefined,
  phonenumber: undefined,
  status: 0,
  deptId: undefined
});

const { width: screenWidth } = useWindowSize();

onMounted(() => {
  getList();
});

const userTableRef = ref(null);

const showDialog = userList => {
  dialogVisible.value = true;
  if (props.noRecord) {
    nextTick(() => {
      userTableRef.value.clearSelection();
    });
    selectedUserList.value = [];
  } else {
    removedSelectRows.value = difference(selectedUserList.value, userList).map(item => item.id);
    selectedUserList.value = userList;
    defaultSelectRows.value = userList.map(item => item.id);
    nextTick(() => {
      handleDefaultRowSelection();
    });
  }
  getTreeselect();
  getRoleList({}, true).then(res => {
    roleList.value = res.data;
  });
};

defineExpose({
  showDialog
});

const getList = () => {
  loading.value = true;
  pageUser(queryParams, true).then(response => {
    userList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
    handleDefaultRowSelection();
  });
};

const handleQuery = () => {
  queryParams.current = 1;
  getList();
};

const queryFormRef = ref(null);

const resetQuery = () => {
  resetFormRef(queryFormRef);
  handleQuery();
};

const handleSelectionChange = selection => {
  selectedUserList.value = uniqBy(selection, "id");
};

const deleteSelectedUserHandle = row => {
  const index = findIndex(selectedUserList.value, ["id", row.id]);
  selectedUserList.value.splice(index, 1);
  const user = userList.value.find(item => item.id == row.id);
  userTableRef.value.toggleRowSelection(user, false);
  removedSelectRows.value.push(row.id);
};

const handleDefaultRowSelection = () => {
  if (defaultSelectRows.value.length === 0 && removedSelectRows.value.length === 0) {
    return;
  }

  userList.value.forEach(user => {
    const index = defaultSelectRows.value.findIndex(item => user.id == item);
    if (index !== -1) {
      userTableRef.value.toggleRowSelection(user, true);
      defaultSelectRows.value.splice(index, 1);
    }

    const index1 = removedSelectRows.value.findIndex(item => user.id == item);
    if (index1 !== -1) {
      nextTick(() => {
        userTableRef.value.toggleRowSelection(user, false);
      });
      removedSelectRows.value.splice(index, 1);
    }
  });
};

const handleSingleUser = user => {
  selectedUserList.value = [user];
};

const submitSelectedUserHandle = () => {
  dialogVisible.value = false;
  emit("submit", selectedUserList.value);
};

const deptOptions = ref(undefined);

const getTreeselect = () => {
  getDeptTree().then(response => {
    deptOptions.value = response.data;
  });
};

const roleList = ref([]);

const moreFilter = ref(false);
</script>
<style scoped lang="scss">
:deep(.el-form--inline .el-form-item) {
  margin-right: 0 !important;
}

.input-width {
  width: 100%;
}

.table-expand {
  padding: 10px;

  .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 100%;
  }
}

.title-text {
  margin-bottom: 10px;
}

@media screen and (max-width: 768px) {
  .app-container {
    padding-bottom: 60px;
  }
}
</style>
